<template>
  <div class="panel-tab__content">
    <div class="panel-tab__content--title">
      <span><i class="el-icon-menu" style="margin-right: 8px; color: #555555"></i>消息列表</span>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="openModel('message')">创建新消息</el-button>
    </div>
    <el-table :data="messageList" size="mini" border>
      <el-table-column type="index" label="序号" width="60px" />
      <el-table-column label="消息ID" prop="id" max-width="300px" show-overflow-tooltip />
      <el-table-column label="名称" prop="name" max-width="300px" show-overflow-tooltip />
      <el-table-column label="操作" min-width="90px">
        <template slot-scope="{ row, $index }">
          <el-button size="mini" type="text" @click="updateMessage(row, $index)">编辑</el-button>
          <el-divider direction="vertical" />
          <el-button size="mini" type="text" style="color: #ff4d4f" @click="removeMessage(row, $index)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="panel-tab__content--title" style="padding-top: 8px; margin-top: 8px; border-top: 1px solid #eeeeee">
      <span><i class="el-icon-menu" style="margin-right: 8px; color: #555555"></i>信号列表</span>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="openModel('signal')">创建新信号</el-button>
    </div>
    <el-table :data="signalList" size="mini" border>
      <el-table-column type="index" label="序号" width="60px" />
      <el-table-column label="信号ID" prop="id" max-width="300px" show-overflow-tooltip />
      <el-table-column label="名称" prop="name" max-width="300px" show-overflow-tooltip />
      <el-table-column label="范围" prop="scope" max-width="100px" show-overflow-tooltip />
      <el-table-column label="操作" min-width="90px" fixed="right">
        <template slot-scope="{ row, $index }">
          <el-button size="mini" type="text" @click="updateSignal(row, $index)">编辑</el-button>
          <el-divider direction="vertical" />
          <el-button size="mini" type="text" style="color: #ff4d4f" @click="removeSignal(row, $index)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="panel-tab__content--title" style="padding-top: 8px; margin-top: 8px; border-top: 1px solid #eeeeee">
      <span><i class="el-icon-menu" style="margin-right: 8px; color: #555555"></i>错误列表</span>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="openModel('error')">创建新错误</el-button>
    </div>
    <el-table :data="errorList" size="mini" border>
      <el-table-column type="index" label="序号" width="60px" />
      <el-table-column label="错误ID" prop="id" max-width="300px" show-overflow-tooltip />
      <el-table-column label="名称" prop="name" max-width="300px" show-overflow-tooltip />
      <el-table-column label="标识" prop="errorCode" max-width="300px" show-overflow-tooltip />
      <el-table-column label="操作" min-width="90px" fixed="right">
        <template slot-scope="{ row, $index }">
          <el-button size="mini" type="text" @click="updateError(row, $index)">编辑</el-button>
          <el-divider direction="vertical" />
          <el-button size="mini" type="text" style="color: #ff4d4f" @click="removeError(row, $index)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="modelVisible" :title="modelConfig.title" :close-on-click-modal="false" width="400px" append-to-body destroy-on-close>
      <el-form :model="modelObjectForm" size="mini" label-width="90px" @submit.native.prevent>
        <el-form-item :label="modelConfig.idLabel">
          <el-input v-model="modelObjectForm.id" clearable >
            <!--id为纯数字时,保存xml会校验不通过-->
            <template slot="prepend" v-if="modelType === 'signal'">Signal__</template>
            <template slot="prepend" v-else-if="modelType === 'message'">Message_</template>
            <template slot="prepend" v-else>Error_</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="modelConfig.nameLabel">
          <el-input v-model="modelObjectForm.name" clearable />
        </el-form-item>
        <el-form-item :label="modelConfig.codeLabel" v-if="modelType === 'error'">
          <el-input v-model="modelObjectForm.errorCode" clearable />
        </el-form-item>
        <el-form-item label="全局信号" v-if="modelType === 'signal'">
          <el-switch v-model="modelObjectForm.scope" active-value="global" inactive-value="processInstance"></el-switch>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button size="mini" @click="modelVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addNewObject">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "SignalMessageErrorPanel",
  data() {
    return {
      signalList: [],
      messageList: [],
      errorList: [],
      modelVisible: false,
      modelType: "",
      modelObjectForm: {
        // 默认当前实例有效
        scope: 'processInstance'
      },
      elementTypeMap: {
        message: "bpmn:Message",
        signal: "bpmn:Signal",
        error: "bpmn:Error",
      },
      prefixMap: {
        message: "Message_",
        signal: "Signal__",
        error: "Error_",
      },
    };
  },
  computed: {
    modelConfig() {
      if (this.modelType === "message") {
        return { title: "消息", idLabel: "消息ID", nameLabel: "消息名称" };
      } else if (this.modelType === "signal") {
        return { title: "信号", idLabel: "信号ID", nameLabel: "信号名称" };
      } else {
        return { title: "错误", idLabel: "错误ID", nameLabel: "错误名称", codeLabel: "错误标识" };
      }
    }
  },
  mounted() {
    this.initDataList();
  },
  methods: {
    initDataList() {
      this.rootElements = this.modelerStore.modeler.getDefinitions().rootElements;
      this.messageIdMap = {};
      this.signalIdMap = {};
      this.errorIdMap = {};
      this.messageList = [];
      this.signalList = [];
      this.rootElements.forEach(el => {
        if (el.$type === "bpmn:Message") {
          this.messageIdMap[el.id] = true;
          this.messageList.push({ ...el });
        }
        if (el.$type === "bpmn:Signal") {
          this.signalIdMap[el.id] = true;
          this.signalList.push({...el});
        }
        if (el.$type === "bpmn:Error") {
          this.errorIdMap[el.id] = true;
          this.errorList.push({...el});
        }
      });
    },
    openModel(type) {
      this.modelType = type;
      this.modelObjectForm = {};
      this.modelVisible = true;
    },
    addNewObject() {
      const elementType = this.elementTypeMap[this.modelType];
      const prefix = this.prefixMap[this.modelType];
      // 检查 id 是否已经以 prefix 开头
      if (this.modelObjectForm.id.indexOf(prefix) !== 0) {
        this.modelObjectForm.id = prefix + this.modelObjectForm.id;
      }
      const elementIndex = this.rootElements.findIndex(element => element.$type === elementType && element.id === this.modelObjectForm.id);
      if (elementIndex > -1) {
        // 更新元素
        this.rootElements[elementIndex] = this.modelerStore.moddle.create(elementType, this.modelObjectForm);
      } else {
        // 新增元素
        const elementRef = this.modelerStore.moddle.create(elementType, this.modelObjectForm);
        this.rootElements.push(elementRef);
      }
      this.modelVisible = false;
      this.initDataList();
    },

    // 编辑消息-对id也进行修改时,会新增新增操作
    updateMessage(attr, index) {
      this.modelType = "message";
      const prefix = "Message_";
      this.modelVisible = true;
      const {id, name} = attr;
      const messageId = id.startsWith(prefix) ? id.substring(prefix.length) : id;
      this.modelObjectForm = index === -1 ? {} : {id: messageId, name};
    },

    // 移除消息
    removeMessage(attr, index) {
      this.$confirm("确认移除该消息吗？", "提示", {
        confirmButtonText: "确 认",
        cancelButtonText: "取 消"
      }).then(() => {
        this.messageList.splice(index, 1);
        this.removeRootElements('bpmn:Message', attr.id);
      }).catch(() => console.info("操作取消"))
    },

    // 编辑信号-对id也进行修改时,会新增新增操作
    updateSignal(attr, index) {
      this.modelType = "signal";
      const prefix = "Signal__";
      this.modelVisible = true;
      const {id, name, scope} = attr;
      const signalId = id.startsWith(prefix) ? id.substring(prefix.length) : id;
      this.modelObjectForm = index === -1 ? {} : {id: signalId, name, scope};
    },

    // 移除信号
    removeSignal(attr, index) {
      this.$confirm("确认移除该信号吗？", "提示", {
        confirmButtonText: "确 认",
        cancelButtonText: "取 消"
      }).then(() => {
        this.signalList.splice(index, 1);
        this.removeRootElements('bpmn:Signal', attr.id);
      }).catch(() => console.info("操作取消"));
    },

    // 编辑错误-对id也进行修改时,会新增新增操作
    updateError(attr, index) {
      this.modelType = "error";
      const prefix = "Error_";
      this.modelVisible = true;
      const {id, name, scope} = attr;
      const signalId = id.startsWith(prefix) ? id.substring(prefix.length) : id;
      this.modelObjectForm = index === -1 ? {} : {id: signalId, name, scope};
    },

    // 移除错误
    removeError(attr, index) {
      this.$confirm("确认移除该错误吗？", "提示", {
        confirmButtonText: "确 认",
        cancelButtonText: "取 消"
      }).then(() => {
        this.errorList.splice(index, 1);
        this.removeRootElements('bpmn:Error', attr.id);
      }).catch(() => console.info("操作取消"));
    },

    // 删除主流程中的元素
    removeRootElements(elementType, elementId) {
      this.rootElements?.forEach((ex, index) => {
        if (ex.$type === elementType && ex.id === elementId) {
          this.rootElements.splice(index, 1);
        }
      });
    },
  }
};
</script>
